package com.xpengplayer.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.xpengplayer.R;
import com.xpengplayer.data.FavoriteDirectory;
import com.xpengplayer.data.FavoriteDirectoryManager;
import com.xpengplayer.data.PlayHistory;
import com.xpengplayer.data.PlayHistoryManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 主界面内容Fragment
 * 显示最近播放记录和收藏目录
 */
public class MainContentFragment extends Fragment {

    private ListView playHistoryListView;
    private ListView favoriteDirectoryListView;
    private TextView noHistoryText;
    private TextView noFavoritesText;
    private Button browseStorageButton;
    
    private PlayHistoryManager historyManager;
    private FavoriteDirectoryManager favoriteManager;
    private List<PlayHistory> playHistoryList;
    private List<FavoriteDirectory> favoriteDirectoryList;
    
    private OnVideoSelectListener videoSelectListener;
    
    // 定义视频选择监听器接口
    public interface OnVideoSelectListener {
        void onVideoSelected(Uri videoUri);
    }
    
    public void setOnVideoSelectListener(OnVideoSelectListener listener) {
        this.videoSelectListener = listener;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_content, container, false);
        
        // 初始化UI组件
        playHistoryListView = view.findViewById(R.id.play_history_list);
        favoriteDirectoryListView = view.findViewById(R.id.favorite_directory_list);
        noHistoryText = view.findViewById(R.id.no_history_text);
        noFavoritesText = view.findViewById(R.id.no_favorites_text);
        browseStorageButton = view.findViewById(R.id.browse_storage_button);
        
        // 初始化管理器
        historyManager = new PlayHistoryManager(getContext());
        favoriteManager = new FavoriteDirectoryManager(getContext());
        
        // 加载数据
        loadPlayHistory();
        loadFavoriteDirectories();
        
        // 设置浏览存储按钮点击事件
        browseStorageButton.setOnClickListener(v -> {
            // 默认打开根目录
            Intent intent = new Intent(getActivity(), DirectoryBrowserActivity.class);
            intent.putExtra(DirectoryBrowserActivity.EXTRA_DIRECTORY_PATH, Environment.getExternalStorageDirectory().getAbsolutePath());
            startActivityForResult(intent, 100);
        });
        
        return view;
    }
    
    @Override
    public void onResume() {
        super.onResume();
        // 每次回到界面都重新加载数据
        loadPlayHistory();
        loadFavoriteDirectories();
    }
    
    /**
     * 加载最近播放记录
     */
    private void loadPlayHistory() {
        List<PlayHistory> allHistory = historyManager.getAllHistory();
        // 最多显示10条记录
        playHistoryList = allHistory.size() > 10 ? allHistory.subList(0, 10) : allHistory;
        
        if (playHistoryList.isEmpty()) {
            playHistoryListView.setVisibility(View.GONE);
            noHistoryText.setVisibility(View.VISIBLE);
        } else {
            playHistoryListView.setVisibility(View.VISIBLE);
            noHistoryText.setVisibility(View.GONE);
            
            // 创建显示列表
            List<String> displayList = new ArrayList<>();
            for (PlayHistory history : playHistoryList) {
                displayList.add(history.getVideoTitle() + " (" + formatTime(history.getPlaybackPosition()) + ")");
            }
            
            // 设置适配器
            ArrayAdapter<String> adapter = new ArrayAdapter<>(
                    getContext(),
                    android.R.layout.simple_list_item_1,
                    displayList
            );
            playHistoryListView.setAdapter(adapter);
            
            // 设置点击事件
            playHistoryListView.setOnItemClickListener((parent, view, position, id) -> {
                PlayHistory history = playHistoryList.get(position);
                Uri videoUri = Uri.parse(history.getVideoPath());
                if (videoSelectListener != null) {
                    videoSelectListener.onVideoSelected(videoUri);
                }
            });
        }
    }
    
    /**
     * 加载收藏目录
     */
    private void loadFavoriteDirectories() {
        favoriteDirectoryList = favoriteManager.getAllFavorites();
        
        if (favoriteDirectoryList.isEmpty()) {
            favoriteDirectoryListView.setVisibility(View.GONE);
            noFavoritesText.setVisibility(View.VISIBLE);
        } else {
            favoriteDirectoryListView.setVisibility(View.VISIBLE);
            noFavoritesText.setVisibility(View.GONE);
            
            // 创建显示列表
            List<String> displayList = new ArrayList<>();
            for (FavoriteDirectory dir : favoriteDirectoryList) {
                displayList.add(dir.getDirectoryName());
            }
            
            // 设置适配器
            ArrayAdapter<String> adapter = new ArrayAdapter<>(
                    getContext(),
                    android.R.layout.simple_list_item_1,
                    displayList
            );
            favoriteDirectoryListView.setAdapter(adapter);
            
            // 设置点击事件
            favoriteDirectoryListView.setOnItemClickListener((parent, view, position, id) -> {
                FavoriteDirectory directory = favoriteDirectoryList.get(position);
                // 打开目录浏览器
                Intent intent = new Intent(getActivity(), DirectoryBrowserActivity.class);
                intent.putExtra(DirectoryBrowserActivity.EXTRA_DIRECTORY_PATH, directory.getDirectoryPath());
                startActivityForResult(intent, 100);
            });
        }
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == getActivity().RESULT_OK && data != null) {
            String videoPath = data.getStringExtra(DirectoryBrowserActivity.EXTRA_SELECTED_VIDEO_PATH);
            if (videoPath != null) {
                Uri videoUri = Uri.fromFile(new File(videoPath));
                if (videoSelectListener != null) {
                    videoSelectListener.onVideoSelected(videoUri);
                }
            }
        }
    }
    
    /**
     * 格式化时间
     */
    private String formatTime(long milliseconds) {
        if (milliseconds < 0) return "00:00";
        long totalSeconds = milliseconds / 1000;
        long minutes = totalSeconds / 60;
        long seconds = totalSeconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }
}